package cn.iocoder.yudao.module.infra.tts;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.module.infra.api.config.IConfigApi;
import cn.iocoder.yudao.module.infra.tts.impl.proxy.ProxyTTS;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;

import java.util.HashMap;
import java.util.Map;

/**
 * ttsName优先级: 请求参数 > 数据库 > 配置文件
 */
@Slf4j
@Component
public class TTSServiceFactory {
    private static final String TTS_PRIMARY = "tts_primary";
    private final Map<String, ITTSApi> serviceMap = new HashMap<>();

    @Resource
    private TTSConfig ttsConfig;
    @Resource
    private IConfigApi configApi;

    @Autowired
    public TTSServiceFactory(Map<String, ITTSApi> ttsServiceMap) {
        ttsServiceMap.forEach((key, value) -> {
            this.serviceMap.put(key, new ProxyTTS(value));
        });
    }

    @PostConstruct
    public void init() {
        log.info("初始化TTS服务, primary = {}", getPrimaryName());
    }

    public String getPrimaryName() {
        String primary = ttsConfig.getPrimary();

        final String primaryFromDB = configApi.getValueByKey(TTS_PRIMARY);
        if (StrUtil.isNotEmpty(primaryFromDB)) {
            primary = primaryFromDB;
        }

        return primary;
    }

    public ITTSApi getService() {
        final String primary = getPrimaryName();
        return getService(primary);
    }

    public ITTSApi getService(String ttsName) {
        return serviceMap.get("tts-" + ttsName);
    }

}
